var mongodb = require('mongodb');
var config  = require(require('fs').existsSync('../config.js') ? '../config.js' : './config.js');
var common  = require('./common.js');
var server  = require('./server.js');
global.util     = require('util');

var CloudShop = require('./cloud/cloudshop.js').CloudShop;
var BattleWorld = require('./cloud/battleworld.js').BattleWorld;
var Replay = require('./world/replay.js').Replay;
var TroopMatch = require('./cloud/troopmatch.js').TroopMatch;
var Activity = require('./cloud/activity.js').Activity;
var ServerMine = require('./cloud/servermine.js').ServerMine;
var LuckyNumber = require('./cloud/activity.js').LuckyNumber;
var Lottery = require('./cloud/lottery.js').Lottery;
var Lottery = require('./cloud/lottery.js').Lottery;
var champsbattle  = require('./cloud/champsbattle.js');
var ChampsBattle = champsbattle.ChampsBattle;

var worldItems = {};

(function main(){
    server.loadConf();
    champsbattle._initRuntime();

    server.loadDB(function(db){
        db.createCollection('user', {}, function(err, result){
        });

        db.createCollection('world', {}, function(err, result){
            global.gDBWorld = db.collection('world');

            CloudShop.create();
            BattleWorld.create();
            Replay.create();
            TroopMatch.create();
            Activity.create();
            ServerMine.create();
            LuckyNumber.create();
            Lottery.create();
            ChampsBattle.create();

            worldItems['battle_world'] = 1; 
            worldItems['cloud_shop'] = 1; 
            worldItems['_replay_autoid'] = 1;
            worldItems['troop_match'] = 1; 
            worldItems['activity'] = 1; 
            worldItems['server_mine'] = 1; 
            worldItems['lucky_number'] = 1; 
            worldItems['lottery'] = 1;
            worldItems[ChampsBattle._id] = 1;
        });

        setTimeout(function(){
            var cursor = db.collection('world').find({},{_id:1});
            cursor.each(function(err, item) {
                if( cursor.isClosed() ) {
                    if( Object.keys(worldItems).length > 0 ) {
                        console.log('error');
                        process.exit(-1);
                    }else{
                        process.exit(0);
                    }
                }else{
                    if( !item ) return;
                    delete worldItems[item._id];
                }
            });
        }, 2000);

    });
})();
